//
//  DatabaseUtil.swift
//  NotePad-CoreData
//
//  Created by Juntaohuang on 2017/9/17.
//  Copyright © 2017年 Maguiqun. All rights reserved.
//

import Foundation
import CoreData
import UIKit

extension NSDate
{
    func getTimeData(Type:Int) ->Int
    {
        let calendar = NSCalendar.current
        //这里注意 swift要用[,]这样方式写
        let com = calendar.dateComponents([.year,.month,.day], from: self as Date)
        switch Type
        {
            case 0:
                return com.day!
            case 1:
                return com.month!
            case 2:
                return com.year!
            default:
                return com.day!
        }
    }
}

func getContext()->NSManagedObjectContext
{
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    return appDelegate.persistentContainer.viewContext
}


func SaveItem(Title:String,Contente:String)->Bool
{
    let Time = NSDate()
    let context=getContext()
    let entity=NSEntityDescription.entity(forEntityName: "Items", in: context)
    let Item = NSManagedObject(entity: entity!, insertInto: context)
    Item.setValue(Title, forKey: "title")
    Item.setValue(Contente, forKey: "content")
    Item.setValue(Time.getTimeData(Type: 0), forKey: "day")
    Item.setValue(Time.getTimeData(Type: 1), forKey: "month")
    Item.setValue(Time.getTimeData(Type: 2), forKey: "year")
    do
    {
        try context.save()
        return true
    }
    catch
    {
        return false
    }
}

func getItems(Counts:inout Int)->[NSManagedObject]?
{
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Items")
    do
    {
        let searchResults = try getContext().fetch(fetchRequest)
        Counts=searchResults.count
        return searchResults as! [NSManagedObject]
    }
    catch
    {
        return nil
    }
}
/*
func  deleteItem()
{
    let context = getContext()
    let entity = NSEntityDescription.entity(forEntityName: <#T##String#>, in: <#T##NSManagedObjectContext#>)
}
*/
func alert(uvc:UIViewController,message:String)
{
    let alert = UIAlertController(title:"提示",message:message,preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "好", style: .cancel, handler: nil))
    uvc.present(alert, animated: true, completion: nil)
}
